package com.dong;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.junit.Test;

/**
 * 业务相关属性
 */
public class ActivitiBussinessDemo {


    /**
     * ProcessEngine对象
     */
    static ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

    @Test
    public void addBusinessKey() {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("myLeave", "1001");
        System.out.println("businessKey====>" + processInstance.getBusinessKey());
    }

    /**
     * 挂起或激活全部流程实例
     * suspend 挂起
     */
    @Test
    public void suspendAllProcessInstance() {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("myLeave")
                .singleResult();
        // 判断该流程定义下所有流程实例是否都是挂起
        boolean suspended = processDefinition.isSuspended();
        // 获取流程定义ID
        String definitionId = processDefinition.getId();
        if (suspended) {
            // 若全是挂起状态则全部激活 param1:流程定义ID, param2:是否激活 param3:激活时间
            repositoryService.activateProcessDefinitionById(definitionId, true, null);
            System.out.println("流程定义id：" + definitionId + "=====> 已激活");
        } else {
            // 若为激活状态则全部挂起
            repositoryService.suspendProcessDefinitionById(definitionId, true, null);
            System.out.println("流程定义id：" + definitionId + "=====> 已挂起");
        }
    }

    /**
     * 激活或挂起单个流程实例
     */
    @Test
    public void suspendSingleProcessInstance() {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId("10001")
                .singleResult();
        // 挂起状态
        boolean suspended = processInstance.isSuspended();
        // 获取流程实例id
        String processInstanceId = processInstance.getId();
        if (suspended) {
            // 若为挂起状态则激活
            runtimeService.activateProcessInstanceById(processInstanceId);
            System.out.println("流程实例id：" + processInstanceId + "======> 已激活");
        } else {
            // 若为激活则挂起
            runtimeService.suspendProcessInstanceById(processInstanceId);
            System.out.println("流程实例id：" + processInstanceId + "======> 已挂起");
        }
    }
}
